package com.eshop.service;

import com.eshop.mapper.RoleMapper;
import com.eshop.mapper.UserMapper;
import com.eshop.pojo.RespBean;
import com.eshop.pojo.Role;
import com.eshop.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class RegisterService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleMapper roleMapper;

    public RespBean UserRegister(User user,String nameZh) {
        if (userMapper.queryUserByName(user.getUsername())!=null){
            return RespBean.error("该账号已存在，注册失败！请重新注册！");
        }
        Integer rid = roleMapper.findRoleIdByNameZh(nameZh);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setIsEnabled(1);
        user.setPassword(encoder.encode(user.getPassword()));
        if (userMapper.saveUser(user)){
            User user1 = userMapper.queryUserByName(user.getUsername());
            Integer uid = user1.getId();
            if (roleMapper.saveUserRole(rid,uid)){
                return RespBean.success("注册成功！");
            }
            return RespBean.error("注册失败！");
        }
        return RespBean.error("注册失败！");
    }
}
